package com.itheima.vms.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.vms.config.SecretProperties;

import com.itheima.vms.domain.PageInfo;
import com.itheima.vms.domain.PageResult;
import com.itheima.vms.domain.dto.UserLoginDto;
import com.itheima.vms.domain.po.SysUser;
import com.itheima.vms.domain.vo.UserLoginVo;
import com.itheima.vms.mapper.SysUserMapper;
import com.itheima.vms.service.ISysUserService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SecretProperties secretProperties;

    @Autowired
    private SysUserMapper sysUserMapper;



    @Override
    public UserLoginVo login(UserLoginDto userLoginDto) throws Exception {
        SysUser sysUser = getBaseMapper().selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getAccount, userLoginDto.getUsername()));

        if(sysUser!=null && userLoginDto.getPassword().equals((sysUser.getPassword()))){
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("id",sysUser.getId());
            dataMap.put("username",sysUser.getAccount());
            dataMap.put("name",sysUser.getName());
            String token = JWTUtil.createToken(dataMap, secretProperties.getJwtBytes());

            UserLoginVo vo = new UserLoginVo();
            vo.setId(sysUser.getId());
            vo.setName(sysUser.getName());
            vo.setUsername(sysUser.getAccount());
            vo.setToken(token);
            return vo;
        }
        return null;
    }

    //添加用户
    @Override
    public void add(SysUser sysUser) {
        getBaseMapper().insert(sysUser);
    }

    //分页查询
    @Override
    public PageResult queryUserByPage(PageInfo<SysUser> pageInfo) {
        Page<SysUser> page = new Page<>(pageInfo.getPage(), pageInfo.getPageSize());
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(pageInfo != null && pageInfo.getGender()!=null,SysUser::getGender,pageInfo != null ? pageInfo.getGender() : null)
                .like(StringUtils.isNotBlank(pageInfo != null ? pageInfo.getName() : null),SysUser::getName,pageInfo != null ? pageInfo.getName() : null);
        Page<SysUser> result = sysUserMapper.selectPage(page, wrapper);
        return new PageResult(result.getRecords(), result.getTotal());
    }





}
